import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
//{baseURL: '/api'}
const instance = axios.create();


// axios 请求拦截
instance.interceptors.request.use(
    config => {
      // 添加Token认证
      const token = localStorage.getItem('token')
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    error => {
      return Promise.reject(error)
    }
)


// axios 相应拦截
instance.interceptors.response.use(
    result => {
      if (result.data.code === 200) {
        return result.data
      }
      ElMessage.error(result.data.message ? `服务异常: ${result.data.message}` : `服务异常1: 状态码${result.data.code}`)
      return Promise.reject(result.data)

    },
    error => {
      if (error.response.status === 70005) {
        ElMessage.error("请先登录")
        router.push('/login')
      } else {
        ElMessage.error(`服务异常2: ${error.message || error.response?.data?.message || '网络错误'}`)
      }
      return Promise.reject(error)
    }
)

export default instance
